# -*- coding: utf-8 -*-
# @author: HRUN
"""
性能测试依赖检查工具
"""

import logging
from typing import Dict, List, Tuple

logger = logging.getLogger(__name__)

def check_server_dependencies(ssh_client, server_name: str, server_ip: str) -> Dict:
    """
    检查服务器依赖
    
    Args:
        ssh_client: SSH客户端连接
        server_name: 服务器名称
        server_ip: 服务器IP
    
    Returns:
        Dict: 检查结果
    """
    try:
        result = {
            'server_name': server_name,
            'server_ip': server_ip,
            'python_version': None,
            'pip_version': None,
            'locust_installed': False,
            'locust_version': None,
            'locust_path': None,
            'dependencies_ready': False,
            'install_commands': [],
            'warnings': [],
            'errors': []
        }
        
        # 检查Python版本
        stdin, stdout, stderr = ssh_client.exec_command('python3 --version')
        python_version = stdout.read().decode().strip()
        if python_version:
            result['python_version'] = python_version
            # 检查Python版本是否满足要求 (3.9+)
            version_parts = python_version.split()[1].split('.')
            if len(version_parts) >= 2:
                major, minor = int(version_parts[0]), int(version_parts[1])
                if major < 3 or (major == 3 and minor < 9):
                    result['warnings'].append(f"Python版本 {python_version} 可能过低，建议使用Python 3.9+")
        else:
            result['errors'].append("无法获取Python版本信息")
        
        # 检查pip版本
        stdin, stdout, stderr = ssh_client.exec_command('pip --version')
        pip_version = stdout.read().decode().strip()
        if pip_version:
            result['pip_version'] = pip_version
        else:
            result['errors'].append("无法获取pip版本信息")
        
        # 检查Locust是否安装
        stdin, stdout, stderr = ssh_client.exec_command('which locust')
        locust_path = stdout.read().decode().strip()
        if locust_path:
            result['locust_installed'] = True
            result['locust_path'] = locust_path
            
            # 检查Locust版本
            stdin, stdout, stderr = ssh_client.exec_command('locust --version')
            locust_version = stdout.read().decode().strip()
            result['locust_version'] = locust_version
            
            # 检查版本是否匹配要求
            if '2.32.1' not in locust_version:
                result['warnings'].append(f"Locust版本 {locust_version} 与推荐版本 2.32.1 不匹配")
        else:
            result['errors'].append("未安装Locust")
            result['install_commands'].append("pip install locust==2.32.1")
        
        # 检查其他依赖
        dependencies = [
            ('requests', 'requests'),
            ('urllib3', 'urllib3'),
            ('gevent', 'gevent'),
            ('psutil', 'psutil')
        ]
        
        for dep_name, pip_name in dependencies:
            stdin, stdout, stderr = ssh_client.exec_command(f'python3 -c "import {dep_name}"')
            if stderr.read().decode().strip():
                result['warnings'].append(f"缺少依赖: {dep_name}")
                result['install_commands'].append(f"pip install {pip_name}")
        
        # 判断依赖是否准备就绪
        result['dependencies_ready'] = (
            result['python_version'] and 
            result['pip_version'] and 
            result['locust_installed'] and 
            len(result['errors']) == 0
        )
        
        return result
        
    except Exception as e:
        logger.error(f"检查服务器依赖失败: {e}")
        return {
            'server_name': server_name,
            'server_ip': server_ip,
            'dependencies_ready': False,
            'errors': [f"检查过程出错: {str(e)}"]
        }

def get_install_script(server_info: Dict) -> str:
    """
    生成安装脚本
    
    Args:
        server_info: 服务器依赖检查结果
    
    Returns:
        str: 安装脚本
    """
    if server_info['dependencies_ready']:
        return "# 所有依赖已准备就绪，无需安装"
    
    script_lines = [
        "#!/bin/bash",
        "# 自动安装性能测试依赖脚本",
        f"# 服务器: {server_info['server_name']} ({server_info['server_ip']})",
        "",
        "# 升级pip",
        "python3 -m pip install --upgrade pip",
        "",
        "# 安装Locust",
        "pip install locust==2.32.1",
        "",
        "# 安装其他依赖",
        "pip install requests urllib3 gevent psutil",
        "",
        "# 验证安装",
        "locust --version",
        "python3 -c \"import requests, urllib3, gevent, psutil; print('所有依赖安装成功')\"",
        ""
    ]
    
    return "\n".join(script_lines)

def format_dependency_report(server_info: Dict) -> str:
    """
    格式化依赖检查报告
    
    Args:
        server_info: 服务器依赖检查结果
    
    Returns:
        str: 格式化的报告
    """
    lines = [
        f"服务器: {server_info['server_name']} ({server_info['server_ip']})",
        "=" * 50,
        ""
    ]
    
    # 基本信息
    if server_info['python_version']:
        lines.append(f"✅ Python版本: {server_info['python_version']}")
    else:
        lines.append("❌ Python版本: 未知")
    
    if server_info['pip_version']:
        lines.append(f"✅ pip版本: {server_info['pip_version']}")
    else:
        lines.append("❌ pip版本: 未知")
    
    if server_info['locust_installed']:
        lines.append(f"✅ Locust已安装: {server_info['locust_version']}")
        lines.append(f"   路径: {server_info['locust_path']}")
    else:
        lines.append("❌ Locust未安装")
    
    lines.append("")
    
    # 警告信息
    if server_info['warnings']:
        lines.append("⚠️ 警告:")
        for warning in server_info['warnings']:
            lines.append(f"   • {warning}")
        lines.append("")
    
    # 错误信息
    if server_info['errors']:
        lines.append("❌ 错误:")
        for error in server_info['errors']:
            lines.append(f"   • {error}")
        lines.append("")
    
    # 安装命令
    if server_info['install_commands']:
        lines.append("📦 需要安装的依赖:")
        for cmd in server_info['install_commands']:
            lines.append(f"   • {cmd}")
        lines.append("")
    
    # 总结
    if server_info['dependencies_ready']:
        lines.append("🎉 所有依赖已准备就绪，可以开始分布式测试！")
    else:
        lines.append("⚠️ 请先安装缺失的依赖后再进行分布式测试")
    
    return "\n".join(lines) 